<!--
 *                                |~~~~~~~|
 *                                |       |
 *                                |       |
 *                                |       |
 *                                |       |
 *                                |       |
 *     |~.\\\_\~~~~~~~~~~~~~~xx~~~         ~~~~~~~~~~~~~~~~~~~~~/_//;~|
 *     |  \  o \_         ,XXXXX),                         _..-~ o /  |
 *     |    ~~\  ~-.     XXXXX`)))),                 _.--~~   .-~~~   |
 *      ~~~~~~~`\   ~\~~~XXX' _/ ';))     |~~~~~~..-~     _.-~ ~~~~~~~
 *               `\   ~~--`_\~\, ;;;\)__.---.~~~      _.-~
 *                 ~-.       `:;;/;; \          _..-~~
 *                    ~-._      `''        /-~-~
 *                        `\              /  /
 *                          |         ,   | |
 *                           |  '        /  |
 *                            \/;          |
 *                             ;;          |
 *                             `;   .       |
 *                             |~~~-----.....|
 *                            | \             \
 *                           | /\~~--...__    |
 *                           (|  `\       __-\|
 *                           ||    \_   /~    |
 *                           |)     \~-'      |
 *                            |      | \      '
 *                            |      |  \    :
 *                             \     |  |    |
 *                              |    )  (    )
 *                               \  /;  /\  |
 *                               |    |/   |
 *                               |    |   |
 *                                \  .'  ||
 *                                |  |  | |
 *                                (  | |  |
 *                                |   \ \ |
 *                                || o `.)|
 *                                |`\\) |
 *                                |       |
 *                                |       |
 *
 * @Descripttion:
 * @version:
 * @Date: 2022-02-22 09:48:35
 * @LastEditors: huzhushan@126.com
 * @LastEditTime: 2022-04-06 15:21:53
 * @Author: huzhushan@126.com
 * @HomePage: https://huzhushan.gitee.io/vue3-element-admin
 * @Github: https://github.com/huzhushan/vue3-element-admin
 * @Donate: https://huzhushan.gitee.io/vue3-element-admin/donate/
 -->

<template>
  <el-breadcrumb class="app-breadcrumb" separator="/">
    <transition-group name="breadcrumb">
      <el-breadcrumb-item v-for="(item, index) in levelList" :key="item.path">
        <span
          v-if="
            item.redirect === 'noRedirect' ||
              index == levelList.length - 1 ||
              item.name === 'Medias'
          "
          :class="{
            'no-redirect':
              item.redirect === 'noRedirect' || item.name === 'Medias',
          }"
        >
          {{ item.meta.title }}
        </span>
        <a
          v-else-if="item.type === 'innerLink'"
          @click.prevent="handleInnerLink(item.path)"
        >
          {{ item.meta.title }}
        </a>
        <a v-else @click.prevent="handleLink(item)">{{ item.meta.title }}</a>
      </el-breadcrumb-item>
    </transition-group>
  </el-breadcrumb>
</template>

<script>
import Vue from 'vue'
import pathToRegexp from 'path-to-regexp'

export default {
  props: {
    type: {
      type: String,
      default: '',
    },
  },
  data() {
    return {
      levelList: null,
    }
  },
  watch: {
    $route(route) {
      // if you go to the redirect page, do not update the breadcrumbs
      if (route.path.startsWith('/redirect/')) {
        return
      }
      this.getBreadcrumb()
    },
  },
  created() {
    Vue.breadcrumb = Vue.prototype.$breadcrumb = this
    this.getBreadcrumb()
  },
  methods: {
    recursionArr(matched, route) {
      const parentRoute = route.meta.parent
      if (parentRoute) {
        if (parentRoute && parentRoute.meta && parentRoute.meta.title) {
          matched.splice(
            matched.findIndex(item => item.name === route.name),
            0,
            parentRoute
          )
          this.recursionArr(matched, parentRoute)
        }
      }
    },
    getBreadcrumb() {
      if (this.type === 'directory') {
        this.levelList = this.getMediaPath()
        return
      }
      // only show routes with meta.title
      let matched = this.$route.matched.filter(
        item => item.meta && item.meta.title
      )
      const first = matched[0]

      if (!this.isHome(first)) {
        matched = [{ path: '/home', meta: { title: '我的工作台' }}].concat(
          matched
        )
      }

      this.recursionArr(matched, this.$route)

      this.levelList = matched.filter(
        item => item.meta && item.meta.title && item.meta.breadcrumb !== false
      )
      if (this.$route.name === 'Medias') {
        this.levelList = [...this.levelList, ...this.getMediaPath()]
      }
    },
    getMediaPath() {
      const MEDIA_EXPLORER_PATH = localStorage.MEDIA_EXPLORER_PATH
      if (MEDIA_EXPLORER_PATH) {
        const arr = []
        const len = MEDIA_EXPLORER_PATH.match(/\//g).length
        for (var i = 1; i <= len; i++) {
          var reg = new RegExp(`([^\/]*\/){${i}}`, 'g')
          arr.push(MEDIA_EXPLORER_PATH.match(reg)[0])
        }

        return arr.map(item => {
          const title = item
            .split('')
            .reverse()
            .join('')
            .match(/\/([^\/]+)\//)
          return {
            type: 'innerLink',
            path: item,
            meta: {
              title: title ? title[1].split('').reverse().join('') : '根目录',
            },
          }
        })
      } else {
        return [
          {
            type: 'innerLink',
            path: '/',
            meta: {
              title: '根目录',
            },
          },
        ]
      }
    },
    isHome(route) {
      const name = route && route.name
      if (!name) {
        return false
      }
      return name.trim().toLocaleLowerCase() === 'Home'.toLocaleLowerCase()
    },
    pathCompile(path) {
      // To solve this problem https://github.com/PanJiaChen/vue-element-admin/issues/561
      const { params } = this.$route
      var toPath = pathToRegexp.compile(path)
      return toPath(params)
    },
    handleLink(item) {
      const { redirect, path } = item
      if (redirect) {
        this.$router.push(redirect)
        return
      }
      this.$router.push(this.pathCompile(path))
    },
    handleInnerLink(path) {
      localStorage.setItem('MEDIA_EXPLORER_PATH', path)
      this.getBreadcrumb()
    },
  },
}
</script>

<style lang="scss" scoped>
.app-breadcrumb.el-breadcrumb {
  font-size: 14px;
  height: 40px;
  line-height: 40px;
  padding: 0 20px;

  .no-redirect {
    color: #97a8be;
    cursor: text;
  }
}
</style>
